package com.aifeng.hassan_food.mine

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.aifeng.base.*
import com.aifeng.common_ui.base.gone
import com.aifeng.common_ui.base.visible
import com.aifeng.common_ui.helper.formatDecimalWhenHave
import com.aifeng.common_ui.helper.getString
import com.aifeng.common_ui.helper.toNotInt
import com.aifeng.common_ui.view.FullyLinearLayoutManager
import com.aifeng.hassan_food.R
import com.aifeng.model.BaseUrl
import com.aifeng.model.CommonData
import com.aifeng.model.OrderData
import com.aifeng.oss.scaleImage
import com.aifeng.utils.DialogHelper.showHintDialog
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.OrderViewModel
import com.jeremyliao.liveeventbus.utils.observe
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.imageResource
import org.jetbrains.anko.include
import org.jetbrains.anko.startActivity
import org.koin.androidx.viewmodel.ext.android.getViewModel

class OrderRefundActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        include<View>(R.layout.layout_list)
        initTitle(title = "退款/售后", divider = false)

        swipe_refresh.isRefreshing = true
        getData(pageNum)
    }

    override fun getViewModel() = getViewModel<OrderViewModel>()

    @SuppressLint("ClickableViewAccessibility")
    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        empty_img.imageResource = R.mipmap.icon_order_no
        empty_hint.text = "暂无相关订单信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.apply {
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去除闪烁
            loadLinear(baseContext, swipe_refresh) {
                if (!isLoadingMore) {
                    isLoadingMore = true
                    getData(pageNum)
                }
            }
        }

        mAdapter = SlimAdapter.create()
            .register<OrderData>(R.layout.item_refund_list) { data, injector ->

                val index = mList.indexOf(data)
                val isLast = index == mList.size - 1

                injector.text(R.id.item_refund_num, "订单编号：${data.orderno}")
                    .text(R.id.item_refund_back, "退款 ¥ ${data.paytotal.formatDecimalWhenHave()}元")
                    .text(R.id.item_refund_done, "退款成功 ¥ ${data.paytotal.formatDecimalWhenHave()}元")
                    .visibility(
                        R.id.item_refund_divider,
                        if (isLast) View.VISIBLE else View.GONE
                    )
                    .clicked(R.id.item_refund_del) { deleteOrder(data.id, index) }
                    .clicked(R.id.item_refund) {
                        startActivity<OrderRefundDetailActivity>(
                            "id" to data.id,
                            "index" to index.toString()
                        )
                    }

                    .with<RecyclerView>(R.id.item_refund_list) {
                        it.apply {
                            // 拦截item中RecyclerView的点击事件
                            setOnTouchListener { _, event ->
                                return@setOnTouchListener injector.findViewById<View>(R.id.item_refund)
                                    .onTouchEvent(event)
                            }

                            isNestedScrollingEnabled = false
                            layoutManager = FullyLinearLayoutManager(baseContext)
                            adapter = SlimAdapter.create()
                                .register<CommonData>(R.layout.item_shop_inner_list_80) { inner, jector ->
                                    jector.text(R.id.item_shop_name, inner.goodsname)
                                        .text(R.id.item_shop_type, "规格：${inner.specs}")
                                        .text(
                                            R.id.item_shop_price,
                                            setHtmlSmall("¥ ${inner.price.formatDecimalWhenHave()}", "¥")
                                        )
                                        .text(R.id.item_shop_num, "x${inner.num}")
                                        .with<ImageView>(R.id.item_shop_img) { view ->
                                            val imgs = inner.goodimg.split(",")
                                            view.loadRoundedImage(url = imgs[0].scaleImage())
                                        }
                                        .visibility(
                                            R.id.item_shop_set,
                                            if (inner.specstype == "package") View.VISIBLE else View.GONE
                                        )
                                }
                        }

                        (it.adapter as SlimAdapter).updateData(data.list)
                    }
            }
            .attachTo(recycle_list)

        observe("refundList") {
            mList.removeAt(it.toNotInt())
            mAdapter.notifyItemRemoved(it.toNotInt())
            empty_view.apply { if (mList.isEmpty()) visible() else gone() }
        }
    }

    private fun deleteOrder(orderId: String, index: Int) {
        showHintDialog(
            title = "删除订单",
            hint = "确定要删除订单吗？"
        ) {
            getViewModel().orderHandle(
                url = BaseUrl.delOrder,
                orderId = orderId,
                userId = getString("userId")
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        mList.removeAt(index)
                        mAdapter.notifyItemRemoved(index)
                        empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                    }
                )
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().orderList(
            page = index,
            state = "5",
            userId = getString("userId"),
            onSuccess = {
                mList.apply {
                    if (index == 1) {
                        clear()
                        pageNum = index
                    }
                    addItems(it)
                    if (count(it) > 0) pageNum++
                }

                mAdapter.updateData(mList)
            },
            onFinally = {
                swipe_refresh.isRefreshing = false
                isLoadingMore = false
                empty_view.apply { if (mList.isEmpty()) visible() else gone() }
            }
        )
    }

    private fun updateList() {
        swipe_refresh.isRefreshing = true

        empty_view.gone()
        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        pageNum = 1
        getData(pageNum)
    }

}
